package cn.tedu.jxc.security;

import cn.tedu.jxc.mapper.UserMapper;
import cn.tedu.jxc.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserVO userVO = userMapper.select(s);
        if (userVO==null){
            String message = "登录失败，用户名不存在！";
            log.debug(message);
            throw new BadCredentialsException(message);
        }

        List<GrantedAuthority> authorities = new ArrayList<>();
        List<String> permissions = userVO.getPermissions();
        for (String permission : permissions) {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission);
            authorities.add(grantedAuthority);
        }
        log.debug("获取的权限:{}",authorities);

        AdminDetails adminDetails = new AdminDetails(
                userVO.getId(),
                userVO.getUsername(),
                userVO.getPassword(),
                userVO.getEnable()==1,
                authorities);
        return adminDetails;
    }
}
